import {RequestMethod} from "../lib/defines";
import {Room} from "../lib/Rooms";
import kurentoClient from "../kurento/client";
import { MediaOptions, MemberBase, RoomBase } from "../utils/types";

export type CreateQuery = {
  // 所属用户
  members: MemberBase[];
  // 所属房间
  room: RoomBase;
  // 媒体设置
  mediaOptions: MediaOptions;
}

// resident: 常驻房间
// temporary: 临时房间
export default function createClassroom (app) {
  const { socket, rooms: lRooms, intercom } = app.locals;
  const { userId } = socket.handshake.query;
  /**
   * 创建一个房间
   */
  socket.on(RequestMethod.create, async function create (data: CreateQuery, cb) {
    const { room, mediaOptions, members } = data;
    const creator = socket.owner;

    // 储存临时房间用户列表
    const __room = lRooms[room.classId] || (
      lRooms[room.classId] = new Room({
        ...room,
        socket,
        creator,
      })
    )

    socket.setInviteUser(members)

    // 媒体信息
    lRooms[room.classId].setMediaOption(mediaOptions);
    __room.setMember(creator)

    const clientUtils = kurentoClient((error) => { });
    app.locals.clientUtils = clientUtils;

    // 创建客户端 - socket 连接
    app.locals.client = await clientUtils.getClient((error, __client) => {});

    // TODO 通知 邀请的成员加入
    members.forEach((__member) => {
      const __socket = intercom[__member.userId];

      // 不需要通知自己
      if (__socket && __member.userId !== userId) {
        const options = { room, creator, mediaOptions };

        /**
         * 1分钟的等待接听时间
         */
        socket
          .to(__socket.id)
          .timeout(60 * 1000)
          .emit('invite', options, (error, [data]) => {
            if (error) {
              // 超时未接听
              return;
            }

            // 通知本人
            socket
              .emit('invited', {
                member: __member,
                status: data.status
              });

            // 通知房间中的其他人
            socket
              .broadcast
              .in(room.classId)
              .emit('invited', {
                member: __member,
                status: data.status
              });
          })
      }
    });

    // 回调
    if (cb) {
      cb({ status: 'ok', resolve: 'created' })
    }
  });
}
